﻿using JustMetClient.Commons;
using JustMetClient.Models.WebApiModels;
using JustMetClient.Tools;
using Azylee.Core.IOUtils.TxtUtils;
using Azylee.Core.Plus.DataUtils.JsonUtils;
using Azylee.Core.ThreadUtils.SleepUtils;
using Azylee.YeahWeb.HttpUtils;
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace JustMetClient.Modules.WebModule
{
    public static class WebApiSendQueue
    {
        public static CancellationToken CancelToken;
        private static ConcurrentQueue<WebSendModel> Queue = new ConcurrentQueue<WebSendModel>();

        public static void Start()
        {
            StartSendQueue();
        }
        /// <summary>
        /// 添加Web发送信息队列数据
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <param name="method">提交方式 0：GET 1：POST</param>
        public static void Add(string url, object data, HttpMethodType method, int retry = 0)
        {
            if (!string.IsNullOrWhiteSpace(url))
                Queue.Enqueue(new WebSendModel()
                {
                    Url = url,
                    Data = new WebDataModel()
                    {
                        Account = R.Account,
                        Mac = R.NetInfo.Mac,
                        MachineName = R.MachineName,
                        CreateTime = DateTime.Now,
                        Data = data,
                    },
                    Method = method,
                    Retry = retry,
                });
        }
        private static void StartSendQueue()
        {
            //启动任务
            Task.Factory.StartNew(() =>
            {
                //设置退出条件
                while (!CancelToken.IsCancellationRequested)
                {
                    //如果通信正常，并且队列中存在元素
                    if (Queue.Any())
                    {
                        //循环进行操作
                        for (int i = 0; i < Queue.Count; i++)
                        {
                            try
                            {
                                WebSendModel model = null;
                                if (Queue.TryDequeue(out model))
                                {
                                    //更新账号和mac地址信息（防止因连接问题导致的信息不正确，发送脏数据）
                                    if (model != null && model.Data != null)
                                    {
                                        model.Data.Account = R.Account;
                                        model.Data.Mac = R.NetInfo.Mac;
                                    }

                                    string result = "";
                                    CookieCollection cookie = new CookieCollection();
                                    //读取成功后，发送相关指令
                                    switch (model.Method)
                                    {
                                        case HttpMethodType.Get:
                                            result = HttpToolPlus.Get(model.Url, ref cookie);
                                            break;
                                        case HttpMethodType.Post:
                                            //TxtTool.Append(@"F:\20180515\data.txt", model.Url);
                                            //TxtTool.Append(@"F:\20180515\data.txt", JsonTool.ToStr(model.Data));
                                            result = HttpToolPlus.PostJson(model.Url, ref cookie, model.Data, Encoding.UTF8);
                                            break;
                                    }
                                    //解析返回值为模型
                                    WebResultModel rsModel = JsonTool.ToObjFromStr<WebResultModel>(result);
                                    //判断返回值是否为空，操作是否成功
                                    if (rsModel != null && rsModel.OK)
                                    {
                                        R.Log.v(string.Format($"WebAPI通信成功 : {model.Url} : 返回 : {rsModel.Code}"));
                                    }
                                    else
                                    {
                                        R.Log.v(string.Format($"WebAPI通信失败 : {model.Url}"));
                                        //如果操作未成功，则根据重试次数重新添加到队列中
                                        if (model.Retry > 0)
                                        {
                                            Add(model.Url, model.Data.Data, model.Method, model.Retry - 1);
                                        }
                                    }
                                }
                            }
                            catch { }
                        }
                    }
                    Sleep.S(R.TimeInterval.WebQueue);
                }
            });
        }
    }
}
